using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AjaxControlToolkit;

namespace SecurityLinkUp.Admin
{
    public partial class Users : System.Web.UI.Page
    {
        // TODO: this might not be the best way of doing this functionality, (lots of server/
        // database round trips to generate user lists) but it works for now, and in the absence 
        // of a good AJAX control, and/or caching technique is a quick and dirty way of acheiving the goal.

        // going to keep a couple of copies of the "all users" array so we can restore it 
        // quicker than having to keep loading it from the DB.  One "original", and a "display"
        // versions we are going to add/remove users from 
        private static SortedList AllUsers;
        private static SortedList AllUsersDisplay;

        // keep a copy of the users checkbox and the admin checkboxes so it's easy to iterate
        // through them when the add/remove buttons are pressed
        private static ArrayList AllUsersCheckboxes;
        private static ArrayList AdminUsersCheckboxes;

        protected void Page_Load(object sender, EventArgs e)
        {
            // before we do anything, ensure that the user has the right
            // role to perform anything on this page
            Security.CheckAdminUser(this);

            if (!Page.IsPostBack)
            {
                // setup vars on first load
                AllUsersCheckboxes = new ArrayList();
                AdminUsersCheckboxes = new ArrayList();
                AllUsers = UserData.GetAllUsers();

                // only display the admin button for super admins
                if (Roles.IsUserInRole("SuperAdmin"))
                {
                    AdminModeChk.Visible = true;
                }

                // force the chapters/community list to load
                TypeList_SelectedIndexChanged(this, null);
            }
            else
            {
                // have to redraw on postback to preserve viewstate
                DrawDisplay();
            }
        }

        private void BuildUserTable(SortedList users, PlaceHolder target, ArrayList controlcache)
        {
            // init the col count
            int currentcol = 0;
            int maxcols = 3;

            // clear the control cache
            controlcache.Clear();

            string chkprefix = target.ID + "-";

            Table tbl = new Table();
            TableRow tr = new TableRow();

            IDictionaryEnumerator itr = users.GetEnumerator();
            while (itr.MoveNext())
            {
                User usr = (User)itr.Value;

                // create a new row if we've reached the max number 
                // of cells across
                if (currentcol == maxcols)
                {
                    tbl.Rows.Add(tr);
                    currentcol = 0;
                    tr = new TableRow();
                }
                
                // add a new user cell
                TableCell td = new TableCell();
                Table layouttable = new Table();
                layouttable.CssClass = "userlayout";

                // cell for the user image
                TableRow imagerow = new TableRow();
                TableCell imagecell = new TableCell();
                Image usrimg = new Image();
                usrimg.ImageUrl = usr.picurl;
                imagecell.Controls.Add(usrimg);
                imagerow.Cells.Add(imagecell);
                layouttable.Rows.Add(imagerow);

                // cell for the selection checkbox
                TableRow checkrow = new TableRow();
                TableCell checkcell = new TableCell();
                CheckBox usrcheck = new CheckBox();
                usrcheck.ID = chkprefix + usr.uid;
                Page.Controls.Add(usrcheck);
                checkcell.Controls.Add(usrcheck);
                checkrow.Cells.Add(checkcell);
                layouttable.Rows.Add(checkrow);

                // add the checkbox id to a lookup array so
                // we can access it again easily
                controlcache.Add(usrcheck.ID);
                
                // cell for the username
                TableRow usrnamerow = new TableRow();
                TableCell usrnamecell = new TableCell();
                usrnamecell.Text = usr.username;
                usrnamerow.Cells.Add(usrnamecell);
                layouttable.Rows.Add(usrnamerow);

                // add the layout to the main table
                td.Controls.Add(layouttable);

                // add the cell to the row
                tr.Cells.Add(td);

                // increment the col count
                currentcol++;
            }

            // add the final row to the table
            tbl.Rows.Add(tr);

            // finished building the table - substitute it into the target container
            target.Controls.Add(tbl);

        }

        protected void ClearDisplay()
        {
            Name.Text = "";
            Description.Text = "";
            AllUsersPlaceholder.Controls.Clear();
            AdminUsersPlaceholder.Controls.Clear();
        }

        protected void TypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetCommunityChaptersList();
        }

        protected void SetCommunityChaptersList()
        {
            ClearDisplay();

            if (TypeList.SelectedValue == "Communities")
            {
                // populate the list with communities
                ChapterCommunityList.Items.Clear();
                ArrayList communities;
                if (!AdminModeChk.Checked)
                {
                    // only show chapters where the user is an admin
                    communities = CommunityData.GetUserAdminCommunities((Guid)Membership.GetUser().ProviderUserKey);
                }
                else
                {
                    // super admin mode - show all communities
                    communities = CommunityData.GetCommunities(CommonData.Status.ANY);
                }
                ChapterCommunityList.Items.Add("");
                foreach (Community c in communities)
                {
                    ListItem itm = new ListItem(c.name + "  [" + c.status.ToString() + "]", c.uid.ToString());
                    ChapterCommunityList.Items.Add(itm);
                }
            }

            if (TypeList.SelectedValue == "Chapters")
            {
                // populate the list with chapers
                ChapterCommunityList.Items.Clear();
                ArrayList chapters;
                if (!AdminModeChk.Checked)
                {
                    // only show chapters where the user is an admin
                    chapters = ChapterData.GetUserAdminChapters((Guid)Membership.GetUser().ProviderUserKey);
                }
                else
                {
                    // super admin mode - show all communities
                    chapters = ChapterData.GetChapters(CommonData.Status.ANY);
                }
                ChapterCommunityList.Items.Add("");
                foreach (Chapter c in chapters)
                {
                    ListItem itm = new ListItem(c.name + "  [" + c.status + "]", c.uid.ToString());
                    ChapterCommunityList.Items.Add(itm);
                }
            }
        }

        protected void AdminModeChk_CheckedChanged(object sender, EventArgs e)
        {
            // force the list to update
            SetCommunityChaptersList();
        }

        protected void ChapterCommunityList_SelectedIndexChanged(object sender, EventArgs e)
        {
            DrawDisplay();
        }

        protected void DrawDisplay()
        {
            // array to hold the current admins for either communities or chapters
            SortedList admins = new SortedList();

            ClearDisplay();

            // dont do anything if it's the blank "holder" item in the list
            if (ChapterCommunityList.SelectedValue == "")
            {
                return;
            }

            if (TypeList.SelectedValue == "Communities")
            {
                // get the community and set the basic properties
                Community c = CommunityData.GetCommunity(new Guid(ChapterCommunityList.SelectedValue));
                Name.Text = c.name;
                Description.Text = c.description;

                // load the admin list
                admins = CommunityData.GetCommunityAdmins(new Guid(ChapterCommunityList.SelectedValue));
                BuildUserTable(admins, AdminUsersPlaceholder, AdminUsersCheckboxes);       

            }

            if (TypeList.SelectedValue == "Chapters")
            {
                // get the chapter and set the basic properties
                Chapter c = ChapterData.GetChapter(new Guid(ChapterCommunityList.SelectedValue));
                Name.Text = c.name;
                Description.Text = c.description;

                // load the admin list
                admins = ChapterData.GetChapterAdmins(new Guid(ChapterCommunityList.SelectedValue));
                BuildUserTable(admins, AdminUsersPlaceholder, AdminUsersCheckboxes);
            }

            // copy the users list
            //AllUsersDisplay.Clear();
            AllUsersDisplay = (SortedList)AllUsers.Clone();

            // go through and remove the users that are in the admins list
            IDictionaryEnumerator itr = admins.GetEnumerator();
            while (itr.MoveNext())
            {
                if (AllUsersDisplay.Contains(itr.Key))
                {
                    AllUsersDisplay.Remove(itr.Key);
                }
            }

            // display all the users
            BuildUserTable(AllUsersDisplay, AllUsersPlaceholder, AllUsersCheckboxes);
            

        }

        protected void AddUsersBtn_Click(object sender, EventArgs e)
        {
            // go through all the users
            foreach (string chkid in AllUsersCheckboxes)
            {
                // find checkbox from ID on the page
                Control ph = Page.Form.FindControl("AllUsersPlaceholder");
                CheckBox chk = (CheckBox)ph.FindControl(chkid);
                if (chk.Checked)
                {
                    // parse out the userid
                    string ctrlid = chk.ID;
                    Guid userid = new Guid(ctrlid.Replace(AllUsersPlaceholder.ID.ToString() + "-", ""));

                    // add them to the admins
                    if (TypeList.SelectedValue == "Communities")
                    {
                        CommunityData.AddCommunityAdmin(new Guid(ChapterCommunityList.SelectedValue), userid);

                    }
                    if (TypeList.SelectedValue == "Chapters")
                    {
                        ChapterData.AddChapterAdmin(new Guid(ChapterCommunityList.SelectedValue), userid);
                    }
                }
            }

            // redraw the display
            DrawDisplay();
        }

        protected void RemoveUsersBtn_Click(object sender, EventArgs e)
        {
            // go through all the users
            foreach (string chkid in AdminUsersCheckboxes)
            {
                // find checkbox from ID on the page
                Control ph = Page.Form.FindControl("AdminUsersPlaceholder");
                CheckBox chk = (CheckBox)ph.FindControl(chkid);
                if (chk.Checked)
                {
                    // parse out the userid
                    string ctrlid = chk.ID;
                    Guid userid = new Guid(ctrlid.Replace(AdminUsersPlaceholder.ID.ToString() + "-", ""));

                    // add them to the admins
                    if (TypeList.SelectedValue == "Communities")
                    {
                        CommunityData.RemoveCommunityAdmin(new Guid(ChapterCommunityList.SelectedValue), userid);

                    }
                    if (TypeList.SelectedValue == "Chapters")
                    {
                        ChapterData.RemoveChapterAdmin(new Guid(ChapterCommunityList.SelectedValue), userid);
                    }
                }
            }

            // redraw the display
            DrawDisplay();
        }
    }
}
